package com.dbtools;

import java.io.Serializable;
import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;

public class ConnectionTools implements Serializable{
    private static String JNDIName = "jdbc/erpdb";
    private static transient DataSource dataSource;


    private static InitialContext getInitialContext()throws NamingException{
    	return new InitialContext();
    }

    public static Connection getConnection()throws NamingException, SQLException{
        if(dataSource == null){
            InitialContext initialcontext = getInitialContext();
            Object obj = initialcontext.lookup(JNDIName);
            dataSource = (DataSource)PortableRemoteObject.narrow(obj, javax.sql.DataSource.class);
            initialcontext.close();
        }
        return dataSource.getConnection();
    }
    
    public static Connection getConnection2()throws NamingException, SQLException{        
        if(dataSource == null){
            InitialContext initialcontext = getInitialContext();            
            Context ctx = (Context) initialcontext.lookup("java:comp/env");        	
        	dataSource = (DataSource)ctx.lookup(JNDIName);
            initialcontext.close();
        }
        return dataSource.getConnection();
    }
}
